package lock.countDownLatch.hospital;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Main {

    public static void main(String[] args) throws Exception{
        long beginTime = System.currentTimeMillis();
        // 创建倒计时锁，2个任务，执行两次countDown()
        CountDownLatch latch = new CountDownLatch(2);
        // 两个任务并发执行，而不是串行
        ExecutorService threadPool = Executors.newFixedThreadPool(2);
        GuaHaoTask guaHaoTask = new GuaHaoTask(latch);
        QuYaoTask quYaoTask = new QuYaoTask(latch);
        threadPool.execute(guaHaoTask);
        threadPool.execute(quYaoTask);
        // 倒计时锁等待任务执行完成，计数器为0时，释放锁，再进行后续操作
        System.out.println("倒计时锁开始等待，计数器为：" + latch.getCount());
        latch.await();
//        latch.await(6, TimeUnit.SECONDS);  // 如果设置锁超时时间，有可能导致任务还没执行完就释放锁，往下执行
        System.out.println("倒计时锁释放，计数器为：" + latch.getCount());
        System.out.println("主线程操作耗时：" + (System.currentTimeMillis() - beginTime));
        System.exit(0);
    }
}
